<template>
  <div class="inpaint">
    <div class="workspace">
      <!-- 左侧参数面板 -->
      <div class="params-panel">
        <el-form label-position="top">
          <!-- 图片上传 -->
          <el-form-item label="上传原图">
            <el-upload
              class="image-upload"
              drag
              :auto-upload="false"
              :show-file-list="false"
              accept="image/*"
              @change="handleImageChange"
            >
              <template #default>
                <div v-if="!sourceImage" class="upload-placeholder">
                  <el-icon :size="24"><Upload /></el-icon>
                  <p>拖拽图片到此处或点击上传</p>
                </div>
                <img v-else :src="sourceImage" class="upload-preview" />
              </template>
            </el-upload>
          </el-form-item>

          <!-- 提示词输入 -->
          <el-form-item label="提示词">
            <el-input
              v-model="prompt"
              type="textarea"
              :rows="4"
              placeholder="描述你想要的修改..."
            />
          </el-form-item>

          <!-- 画笔设置 -->
          <el-form-item label="画笔大小">
            <el-slider v-model="brushSize" :min="5" :max="50" />
          </el-form-item>

          <el-form-item label="画笔硬度">
            <el-slider v-model="brushHardness" :min="0" :max="100" />
          </el-form-item>

          <!-- 其他参数... -->
          <el-form-item>
            <el-button 
              type="primary" 
              :loading="generating" 
              :disabled="!sourceImage || !maskImage"
              @click="handleGenerate" 
              style="width: 100%"
            >
              生成图片
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 右侧编辑区 -->
      <div class="edit-panel">
        <div class="toolbar">
          <el-radio-group v-model="tool" size="small">
            <el-radio-button label="brush">画笔</el-radio-button>
            <el-radio-button label="eraser">橡皮擦</el-radio-button>
          </el-radio-group>
          <el-button size="small" @click="clearMask">清除遮罩</el-button>
        </div>

        <div class="canvas-container">
          <!-- 原图层 -->
          <canvas 
            ref="sourceCanvas"
            class="canvas source-canvas"
            :width="canvasWidth"
            :height="canvasHeight"
          ></canvas>
          
          <!-- 遮罩层 -->
          <canvas 
            ref="maskCanvas"
            class="canvas mask-canvas"
            :width="canvasWidth"
            :height="canvasHeight"
            @mousedown="startDrawing"
            @mousemove="draw"
            @mouseup="stopDrawing"
            @mouseleave="stopDrawing"
          ></canvas>
        </div>

        <!-- 生成结果 -->
        <div v-if="generatedImage" class="result">
          <h3>生成结果</h3>
          <img :src="generatedImage" alt="Generated image" />
          <div class="result-actions">
            <el-button-group>
              <el-button type="primary" @click="handleSave">
                <el-icon><Download /></el-icon>
                保存
              </el-button>
              <el-button type="primary" @click="handleShare">
                <el-icon><Share /></el-icon>
                分享
              </el-button>
            </el-button-group>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { Picture, Upload, Download, Share } from '@element-plus/icons-vue'
import { useImageStore } from '../stores/image'

const imageStore = useImageStore()

// 画布相关
const sourceCanvas = ref<HTMLCanvasElement | null>(null)
const maskCanvas = ref<HTMLCanvasElement | null>(null)
const canvasWidth = ref(512)
const canvasHeight = ref(512)

// 表单数据
const sourceImage = ref('')
const maskImage = ref('')
const prompt = ref('')
const brushSize = ref(20)
const brushHardness = ref(50)
const tool = ref('brush')

// 绘画状态
const isDrawing = ref(false)
const lastX = ref(0)
const lastY = ref(0)

// 生成状态
const generating = ref(false)
const generatedImage = ref('')

// 处理图片上传
const handleImageChange = (file: any) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    sourceImage.value = e.target?.result as string
    // 加载图片到画布
    const img = new Image()
    img.onload = () => {
      if (sourceCanvas.value) {
        const ctx = sourceCanvas.value.getContext('2d')
        ctx?.drawImage(img, 0, 0, canvasWidth.value, canvasHeight.value)
      }
    }
    img.src = e.target?.result as string
  }
  reader.readAsDataURL(file.raw)
}

// 开始绘制
const startDrawing = (e: MouseEvent) => {
  isDrawing.value = true
  const rect = (e.target as HTMLCanvasElement).getBoundingClientRect()
  lastX.value = e.clientX - rect.left
  lastY.value = e.clientY - rect.top
}

// 绘制
const draw = (e: MouseEvent) => {
  if (!isDrawing.value || !maskCanvas.value) return

  const ctx = maskCanvas.value.getContext('2d')
  if (!ctx) return

  const rect = maskCanvas.value.getBoundingClientRect()
  const x = e.clientX - rect.left
  const y = e.clientY - rect.top

  ctx.beginPath()
  ctx.moveTo(lastX.value, lastY.value)
  ctx.lineTo(x, y)
  ctx.strokeStyle = tool.value === 'brush' ? 'white' : 'black'
  ctx.lineWidth = brushSize.value
  ctx.lineCap = 'round'
  ctx.stroke()

  lastX.value = x
  lastY.value = y

  // 更新遮罩图片
  maskImage.value = maskCanvas.value.toDataURL('image/png')
}

// 停止绘制
const stopDrawing = () => {
  isDrawing.value = false
}

// 清除遮罩
const clearMask = () => {
  if (maskCanvas.value) {
    const ctx = maskCanvas.value.getContext('2d')
    ctx?.clearRect(0, 0, canvasWidth.value, canvasHeight.value)
    maskImage.value = ''
  }
}

// 生成图片
const handleGenerate = async () => {
  if (!sourceImage.value || !maskImage.value) return
  
  generating.value = true
  try {
    const result = await imageStore.generateImage(prompt.value, {
      init_image: sourceImage.value,
      mask: maskImage.value
    })
    generatedImage.value = result.imageUrl
  } catch (error) {
    console.error('Generation failed:', error)
  } finally {
    generating.value = false
  }
}

// 保存图片
const handleSave = () => {
  const link = document.createElement('a')
  link.href = generatedImage.value
  link.download = 'inpainted-image.png'
  link.click()
}

// 分享图片
const handleShare = () => {
  // 实现分享功能
}

// 初始化画布
onMounted(() => {
  if (maskCanvas.value) {
    const ctx = maskCanvas.value.getContext('2d')
    if (ctx) {
      ctx.fillStyle = 'black'
      ctx.fillRect(0, 0, canvasWidth.value, canvasHeight.value)
    }
  }
})
</script>

<style scoped lang="scss">
.inpaint {
  height: 100%;
}

.workspace {
  display: flex;
  gap: 20px;
  height: 100%;
}

.params-panel {
  width: 300px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  overflow-y: auto;

  .image-upload {
    width: 100%;
    
    .upload-placeholder {
      text-align: center;
      color: #999;
      padding: 20px 0;
      
      p {
        margin-top: 8px;
      }
    }

    .upload-preview {
      width: 100%;
      height: 200px;
      object-fit: cover;
    }
  }
}

.edit-panel {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;

  .toolbar {
    display: flex;
    gap: 12px;
    align-items: center;
  }

  .canvas-container {
    flex: 1;
    position: relative;
    border: 1px solid #eee;
    border-radius: 4px;
    overflow: hidden;

    .canvas {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }

    .source-canvas {
      z-index: 1;
    }

    .mask-canvas {
      z-index: 2;
      opacity: 0.5;
    }
  }

  .result {
    h3 {
      margin: 0 0 12px;
      color: #666;
    }

    img {
      width: 100%;
      border-radius: 4px;
    }

    .result-actions {
      margin-top: 12px;
      text-align: center;
    }
  }
}
</style> 